import { useDispatch, useSelector, shallowEqual } from "react-redux";
import { bindActionCreators } from "redux";
import { query as request } from '@shell-ui/utils';

const __station = (method, params) => {
  const [api, body, options = {}] = params;

  const methodHandler = request[method];

  return (dispatch, getState) => {
    const inject = {
      dispatch,
      getState
    };
    return methodHandler(api, body, { ...inject, ...options });
  }
}

const queryActions = {};
Object.keys(request).forEach((method) => {
  queryActions[method] = (...params) => __station(method, params);
});

const useQuery = (selector) => {
  const result = [];

  if(!_.isEqual(selector)) {
    const reduxState = useSelector(selector, shallowEqual);
    result.push(reduxState);
  }

  const dispatch = useDispatch();
  const query = bindActionCreators({ ...queryActions }, dispatch);
  result.push(query);

  return result;
}

export default useQuery;
